package com.ustc.hewei.loginmodule.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.ustc.hewei.commonmodule.dto.LoginFormDTO;
import com.ustc.hewei.commonmodule.dto.Result;
import com.ustc.hewei.commonmodule.dto.UserDTO;
import com.ustc.hewei.commonmodule.entity.User;
import com.ustc.hewei.commonmodule.mapper.UserMapper;
import com.ustc.hewei.commonmodule.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ustc.hewei.loginmodule.utils.Constants;
import com.ustc.hewei.loginmodule.utils.RegexUtils;
import com.ustc.hewei.nettyrpc2_0.common.annotation.RPCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ustc.hewei.loginmodule.utils.Constants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hewei
 * @since 2022-10-05
 */
@RPCService(value = IUserService.class)
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone) {
        if (!RegexUtils.isValidPhone(phone)) {
            return Result.fail("请输入正确的手机号码！");
        }
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, Constants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.debug("发送验证码成功！验证码：" + code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        String phone = loginForm.getPhone();
        if (!RegexUtils.isValidPhone(phone)) {
            return Result.fail("手机号不正确!");
        }
        String code = loginForm.getCode();
        if (loginForm.getCode() == null || !code.equals(stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone))) {
            return Result.fail("验证码不正确！");
        }
        User user = query().eq("phone", phone).one();
        if (user == null) {
            user = creatUserByPhone(phone);
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String oldToken = stringRedisTemplate.opsForValue().get(USER_TOKEN_KEY + userDTO.getId());
        if (oldToken != null) {
            return Result.ok(oldToken);
        }
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).
                        setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        //设置有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(USER_TOKEN_KEY + userDTO.getId(), token);
        stringRedisTemplate.expire(USER_TOKEN_KEY + userDTO.getId(), LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result logout(UserDTO userDTO) {
        String token = stringRedisTemplate.opsForValue().get(USER_TOKEN_KEY + userDTO.getId());
        stringRedisTemplate.delete(LOGIN_USER_KEY + token);
        stringRedisTemplate.delete(USER_TOKEN_KEY + userDTO.getId());
        return Result.ok();
    }

    @Override
    public Result queryUserDTOByIds(List<Long> ids) {
        String idsStr = StrUtil.join(",", ids);
        // 在这里需要按照点赞的先后顺序来返回，所以不能简单地用listById来进行查询，需要自己手写sql
        // 手写排序规则，规则就是从redis中查到的按照时间戳的排序，所以将redis中的顺序拼接成字符串放到sql中
        List<User> userList = query().in("id", ids).last("ORDER BY FIELD(id, " + idsStr + ")")
                .list();
        List<UserDTO> userDTOS = userList.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    private User creatUserByPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(8));
        save(user);
        return user;
    }
}
